441. Arranging Coins

1. Question

You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.

Given the integer n, return the number of complete rows of the staircase you will build.

2. Examples

Example 1:

img
Image
Input: n = 5
Output: 2
Explanation: Because the 3rd row is incomplete, we return 2.

Example 2:

img
Image
Input: n = 8
Output: 3
Explanation: Because the 4th row is incomplete, we return 3.

3. Constraints

  • 1 <= n <= 231 - 1

4. References

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/arranging-coins 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

5. Solutions

三角形乘2得到矩形情况,然后根据求和公式计算行数。

class Solution {
  public int arrangeCoins(int n) {
    if(n <= 1) {
      return n;
    }
    long sum = 2 * (long)n;
    System.out.println(sum);
    long ans = 1;
    while (ans * (ans + 1) <= sum) {
      ans++;
    }
    return (int) --ans;
  }
}

官方题解:

网址

class Solution {
  public int arrangeCoins(int n) {
    return (int) ((Math.sqrt((long) 8 * n + 1) - 1) / 2);
  }
}
Copyright © rootwhois.cn 2021-2022 all right reserved,powered by GitbookFile Modify: 2023-03-05 10:55:51

results matching ""

    No results matching ""